package com.zhn.util;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

//1、加密算法有 4 种：AES、DES、DESede、RSA
//2、反馈模式有两种：CBC(有向量模式)、ECB(无向量模式)
//3、填充方案有 5 种：NoPadding 、PKCS5Padding、PKCS1Padding 、OAEPWithSHA-1AndMGF1Padding、OAEPWithSHA-256AndMGF1Padding
//4、NoPadding 填充方案: 加密内容不足8位时用0补足8位, Cipher类不提供补位功能，需自己实现代码给加密内容添加0, 如{65,65,65,0,0,0,0,0}
//5、PKCS5Padding 填充方案: 加密内容不足8位用余位数补足8位, 如{65,65,65,5,5,5,5,5}或{97,97,97,97,97,97,2,2}.

public class EncrUtil {

    public static void main(String[] args) throws Exception {
        String plainText = "Hello, World!";
        String key = "ThisIsSecretKey1234567890"; // 密钥长度必须是24个字符
        byte[] encrypt = encrypt(plainText, key);
        String encryptedText = Base64.getEncoder().encodeToString(encrypt);
        System.out.println("Encrypted Text: " + encryptedText);
        String decryptedText = decrypt(encrypt, key);
        System.out.println("Decrypted Text: " + decryptedText);
    }

    /**
     *  加密算法
     * @param plainText
     * @param key
     * @return
     * @throws Exception
     */
    public static byte[] encrypt(String plainText, String key) throws Exception {
        byte[] keyBytes = key.getBytes(StandardCharsets.UTF_8);
        DESedeKeySpec spec = new DESedeKeySpec(keyBytes);
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DESede");
        SecretKey secretKey = keyFactory.generateSecret(spec);
        Cipher cipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);

        return cipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8));
    }

    /**
     * 解密算法
     * @param encryptedBytes
     * @param key
     * @return
     * @throws Exception
     */
    public static String decrypt(byte[] encryptedBytes, String key) throws Exception {
        byte[] keyBytes = key.getBytes(StandardCharsets.UTF_8);
        DESedeKeySpec spec = new DESedeKeySpec(keyBytes);
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DESede");
        SecretKey secretKey = keyFactory.generateSecret(spec);
        //第一段是加密算法的名称  第二段是分组加密的模式  第三段是指最后一个分组的填充方式
        //3DES则要求24字节
        //DESede是3DES算法
        Cipher cipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");
//        Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, secretKey);
        byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
        return new String(decryptedBytes, StandardCharsets.UTF_8);
    }
}